package com.avic.rong;

import android.Manifest;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.MessageQueue;
import android.os.PersistableBundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.avic.rong.activity.login.LoginPhoneActivity;
import com.avic.rong.api.HttpPostService;
import com.avic.rong.api.my_message.UnReadMessageCountApi;
import com.avic.rong.bean.CartListReloadEvent;
import com.avic.rong.bean.GoCartListEvent;
import com.avic.rong.bean.HomePageEvent;
import com.avic.rong.bean.MinePageEvent;
import com.avic.rong.course.FragmentCultivate;
import com.avic.rong.fragment.FragmentAchievements;
import com.avic.rong.fragment.FragmentFollow;
import com.avic.rong.fragment.FragmentHome;
import com.avic.rong.fragment.FragmentMine;
import com.avic.rong.fragment.FragmentMyMessage;
import com.avic.rong.fragment.FragmentRecommendLayzed;
import com.avic.rong.fragment.FragmentStandard;
import com.avic.rong.fragment.FragmentWenDa;
import com.avic.rong.fragment.fragmentshop.fragment.ShopFragment;
import com.avic.rong.listener.RocketOnScrollListener;
import com.avic.rong.userOrder.MineFragmentEvent;
import com.avic.rong.userOrder.MineMessageEvent;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.DialogCustom;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.utils.http.UpdateAppHttpUtil;
import com.avic.rong.utils.permission.PermissionCallBack;
import com.avic.rong.utils.permission.PermissionManager;
import com.avic.rong.wedgit.ForbidSlideViewPager;
import com.coorchice.library.SuperTextView;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.example.minato.minastore.utils.AppUtils;
import com.microquation.linkedme.android.LinkedME;
import com.orhanobut.logger.Logger;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;
import com.vector.update_app.listener.ExceptionHandler;
import com.vector.update_app.utils.AppUpdateUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


public class MainActivity extends RxAppCompatActivity implements View.OnClickListener, RocketOnScrollListener.ScrollCallBackInterface {

    public static final String ARG_FRAGMENTINDEX = "fragmentIndex";
    public static final String ARG_FRAGMENTINDEX_SECOND = "fragmentIndexSecond";
    public static final String TAG = MainActivity.class.getSimpleName();
    private long lastTime;//退出键的最后时间

    /*   // 三个Tab，每个Tab包含一个按钮
       private LinearLayout mTabEducation;
       private LinearLayout mTabFrd;
       private LinearLayout mTabSetting;
       // 三个按钮
       private ImageButton mEducationImg;
       private ImageButton mFrdImg;
       private ImageButton mSettingImg;*/
  /*  private ViewPager mViewPager;// 用来放置界面切换
    private FrameLayout id_content;*/
    private ImageButton ivbtn_home;
    private TextView tv_home;
    private FrameLayout ll_home;
    private ImageView ivbtn_mall;
    private TextView iv_mall;
    private LinearLayout ll_mall;
    private ImageView ivbtn_message;
    private TextView tv_message;
    private LinearLayout ll_message;
    private ImageView ivbtn_mine;
    private TextView tv_mine;
    private LinearLayout ll_mine;

    private int mineClick = 0;
    private int mallClick = 0;
    private boolean clickHomeBtnToTopFlag = false;//点击home按钮到达顶部

    /**
     * 基本权限管理
     */

    private final String[] BASIC_PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.ACCESS_FINE_LOCATION
    };
    private SuperTextView tv_badge_view;

    private View statusBarView;
    private int accountCount;
    private int kefuCount;
    private LinearLayout ll_home_normal;
    private ImageView iv_home_click;
    private LinearLayout ll_home_click;

    private boolean homeIconSwitcher = false;

    private Animation animation;
    private int currentFragmentIndex = 0;
    private String currentHomeFragmentIndexStr = "推荐";

    private ArrayList<Fragment> fragments;
    private FragmentHome fragmentHome;
    private ShopFragment shopFragment;
    private FragmentMyMessage fragmentMyMessage;
    private FragmentMine fragmentMine;
    private ForbidSlideViewPager mainViewPager;
    private int selectPosition = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
        overridePendingTransition(R.anim.center_in, 0);
        setContentView(R.layout.activity_main);

        currentFragmentIndex = getIntent().getIntExtra(ARG_FRAGMENTINDEX, 0);
        currentHomeFragmentIndexStr = getIntent().getStringExtra(ARG_FRAGMENTINDEX_SECOND);

        initView();

        if (currentFragmentIndex == 1) { //link me skip 1
//            eventSwitch(1, ll_mall, ivbtn_mall);
            switchFragment(1);
        } else {
//            eventSwitch(currentFragmentIndex, ll_home_normal, iv_home_click);
            switchFragment(0);

        }
        if (SharedPreferencesUtil.isLogin()) {
            UnReadMessageCountApi unReadMessageCountApi = new UnReadMessageCountApi(MainActivity.this, unMessageListener);//账户消息
            unReadMessageCountApi.setToken(SharedPreferencesUtil.getLoginToken());
            HttpManager.getInstance().doHttpDeal(unReadMessageCountApi);
        } else {
            tv_badge_view.setVisibility(View.INVISIBLE);
        }


        requestNeedPermissions();
        apkUpdateSetUp();//检测版本更新

        //延时加载数据.
        Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
            @Override
            public boolean queueIdle() {
                if (isStatusBar()) {
                    initStatusBar();
                    getWindow().getDecorView().addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
                        @Override
                        public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                            initStatusBar();
                        }
                    });
                }
                //只走一次
                return false;
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        LinkedME.getInstance().setImmediate(true);
    }

/*    public void switchFragment(int viewId) {
//        if (viewId == R.id.rbtn_home) {
//            initViewPage(0);
//        } else if (viewId == R.id.rbtn_mine) {
//            initViewPage(3);
//        }
    }*/

    protected boolean isStatusBar() {
        return true;
    }

    private void initStatusBar() {
        if (statusBarView == null) {
            int identifier = getResources().getIdentifier("statusBarBackground", "id", "android");
            statusBarView = getWindow().findViewById(identifier);
        }
        if (statusBarView != null) {
            statusBarView.setBackgroundResource(R.drawable.status_bar_title);
        }
    }

    //账户消息
    HttpOnNextListener<BaseResultEntity> unMessageListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (!baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(baseResultEntity.getMsg());
            }
            if (baseResultEntity.getData() != null) {
                double data = (double) baseResultEntity.getData();
                accountCount = (int) data;
            }
            //获取客服消息
            getKeFuMsgCount();
        }
    };

    private void getKeFuMsgCount() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(AppUtils.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        HttpPostService httpPostService = retrofit.create(HttpPostService.class);

        Observable<Double> observable = httpPostService.unReadKeFuMessageCount(SharedPreferencesUtil.getLoginToken());

        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Double>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Double aDouble) {
                        kefuCount = aDouble.intValue();
                        Log.e("msg", "kefuCount: " + kefuCount);
                        Log.e("msg", "accountCount: " + accountCount);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (kefuCount + accountCount > 0) {
                                    tv_badge_view.setVisibility(View.VISIBLE);
                                } else {
                                    tv_badge_view.setVisibility(View.INVISIBLE);
                                }
                            }
                        });
                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastTools.showToast(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    /**
     * 申请必要的权限
     */
    private void requestNeedPermissions() {
        /**
         * 启动页适合全部申请成功才能进入
         */
        PermissionManager.getInstance().requestEachCombined(this, new PermissionCallBack() {
            @Override
            public void onGranted(String permissionName) {

                requestPermissionDenied();
            }

            @Override
            public void onDenied(String permissionName) {

                Toast.makeText(MainActivity.this, "请授权该应用必要权限!", Toast.LENGTH_LONG).show();
                requestPermissionGranted();
            }

            @Override
            public void onDeniedWithNeverAsk(String permissionName) {
                //TODO 应该引导用户跳转到权限管理页面，有时间处理
                Log.e(TAG, permissionName);
                Toast.makeText(MainActivity.this, "请授权该应用缺少的必要权限", Toast.LENGTH_SHORT).show();

            }
        }, Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION);
    }

    /**
     * 权限申请成功
     */
    private void requestPermissionDenied() {

    }


    /**
     * 拒绝权限
     */
    private void requestPermissionGranted() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        }, 1500);
    }


    private HttpOnNextListener listener = new HttpOnNextListener<BaseResultEntity>() {

        @Override
        public void onNext(BaseResultEntity entity) {
            System.out.println("-----------------------" + entity.getMsg());
        }
    };

    //商城显示
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void goCartListEvent(GoCartListEvent cartListEvent) {

        switchFragment(1);
        EventBus.getDefault().removeStickyEvent(GoCartListEvent.class);
    }

    /**
     * 首页显示event
     *
     * @param homePageEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void goHomePage(HomePageEvent homePageEvent) {

        switchFragment(0);
        EventBus.getDefault().removeStickyEvent(HomePageEvent.class);
    }

    /**
     * 我的融融显示
     *
     * @param minePageEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void goMinePage(MinePageEvent minePageEvent) {

        switchFragment(3);

        EventBus.getDefault().removeStickyEvent(MinePageEvent.class);
    }

    /* 消息显示*/
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void goMyMessagePage(CartListReloadEvent cartListReloadEvent) {

        switchFragment(2);

        EventBus.getDefault().removeStickyEvent(CartListReloadEvent.class);
    }

    /**
     * 点击“订单列表返回”切换到我的fragment
     *
     * @param mineFragmentEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void backMine(MineFragmentEvent mineFragmentEvent) {
        EventBus.getDefault().removeStickyEvent(MineFragmentEvent.class);

    }

    @Override
    protected void onStart() {
        super.onStart();
        System.out.println("---------------onStart");
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }


    }

    private void apkUpdateSetUp() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("type", "0");
        params.put("channelSource", "");

        new UpdateAppManager
                .Builder()
                //当前Activity
                .setActivity(this)
                //更新地址
                .setUpdateUrl(AppUtils.BASE_URL + AppUtils.URL_APK_UPDATE)
                .handleException(new ExceptionHandler() {
                    @Override
                    public void onException(Exception e) {
                        e.printStackTrace();
                    }
                })
                //实现httpManager接口的对象
                .setHttpManager(new UpdateAppHttpUtil())
                .setParams(params)
                .setPost(true)
                .setThemeColor(ContextCompat.getColor(MainActivity.this, R.color.update_theme_color))
                .setTopPic(R.mipmap.top_8)
                .build().checkNewApp(new CheckNewCallBack());
    }

    public class CheckNewCallBack extends UpdateCallback {
        @Override
        protected void noNewApp(String error) {
//            ToastTools.showToast(MainActivity.this, error);
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("dd", "onActivityResult() called with: requestCode = [" + requestCode + "], resultCode = [" + resultCode + "], data = [" + data + "]");
        switch (resultCode) {
            case Activity.RESULT_CANCELED:
                switch (requestCode) {
                    // 得到通过UpdateDialogFragment默认dialog方式安装，用户取消安装的回调通知，以便用户自己去判断，比如这个更新如果是强制的，但是用户下载之后取消了，在这里发起相应的操作
                    case AppUpdateUtils.REQ_CODE_INSTALL_APP:
//                        Toast.makeText(this,"用户取消了安装包的更新", Toast.LENGTH_LONG).show();
                        break;
                }
                break;
            default:
        }
    }


    private AtomicBoolean isBack;//判断用户是否按了返回键
    private boolean pressBackToExit;// 按返回键是否要退出程序


    @Override
    public void onStop() {
        super.onStop();
        System.out.println("---------------onStop");
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    int clickedBackCount = 0;

    @Override
    public void onBackPressed() {
        clickedBackCount++;
        if (clickedBackCount >= 2) {
//            moveTaskToBack(true);
            DialogCustom.showDoubleDialog(this, "提示", "您确定要退出吗？", "再逛逛", "狠心离开", new DialogCustom.CustomDialogDouble() {
                @Override
                public void rightButtonClicked() {
                    moveTaskToBack(true);
//                    Process.killProcess(Process.myPid());
                    System.exit(0);
                    finish();
                }

                @Override
                public void leftButtonClicked() {

                }
            });
        } else {
            ToastTools.showPublicToast(getResources().getString(R.string.exit_confirm_warm));
        }
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                clickedBackCount = 0;
            }
        }, 2000);
    }

//    @Override
//    public void overridePendingTransition(int enterAnim, int exitAnim) {
//        super.overridePendingTransition(R.anim.center_in, R.anim.center_out);
//    }

    private boolean tipFirstHomeClick = true;
    private boolean tipFirstShopClick = false;
    private boolean tipFirstMessageClick = false;
    private boolean tipFirstMineClick = false;



    private List<Boolean> btnClockList = new ArrayList<>();
    private void setCurrentItem(int postion){
        for(int index = 0; index < btnClockList.size(); index++){
            if (index == postion){
                btnClockList.set(index, true);
            }else{
                btnClockList.set(index,false);
            }
        }
    }

    /*
     * 判断哪个要显示，及设置按钮图片
     */
    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.ll_home:

                homeIconSwitcher = !homeIconSwitcher;

                if (homeIconSwitcher) {
                    iv_home_click.setImageResource(R.mipmap.activity_home_active_rocket);
                    //使用AnimationUtils类的静态方法loadAnimation()来加载XML中的动画XML文件
                    animation = AnimationUtils.loadAnimation(this, R.anim.home_translate_anim_up);
                } else {
                    iv_home_click.setImageResource(R.mipmap.activity_home_active);
                    //使用AnimationUtils类的静态方法loadAnimation()来加载XML中的动画XML文件
                    animation = AnimationUtils.loadAnimation(this, R.anim.home_translate_anim_below);
                    clickHomeBtnToTopFlag = true;

                }
                animation.setFillAfter(true);
                iv_home_click.startAnimation(animation);
                System.out.println("--------------------------main");


                switchFragment(0);


//                if (tipFirstHomeClick){
//                    //点击刷新home首页数据
//                    homeRefresh();
//                }
//                tipFirstHomeClick = true;
//                tipFirstShopClick = false;
//                tipFirstMessageClick = false;
//                tipFirstMineClick = false;

                if (btnClockList.get(0)){
                    //点击刷新home首页数据
                    homeRefresh();
                    Logger.i("-------------------------首页");
                }
                setCurrentItem(0);


                break;
            case R.id.ll_mall:


                btnAnimation(ll_mall);

                switchFragment(1);


//                if (tipFirstShopClick){
//                    //点击刷新商城数据
//                    mallRefresh();
//                }
//                tipFirstHomeClick = false;
//                tipFirstShopClick = true;
//                tipFirstMineClick = false;
//                tipFirstMessageClick = false;

                if (btnClockList.get(1)){
                    //点击刷新商城数据
                    mallRefresh();
                }
                setCurrentItem(1);

                break;
            case R.id.ll_message:

                if (!SharedPreferencesUtil.isLogin()) {
                    startActivity(LoginPhoneActivity.getIntent(MainActivity.this, "CartListReloadEvent"));
                }
                tv_badge_view.setVisibility(View.INVISIBLE);
                EventBus.getDefault().post(kefuCount);
                btnAnimation(ll_message);


                switchFragment(2);


//                if (tipFirstMessageClick){
//                    //点击刷新消息数据
//                    MineMessageEvent mineMessageEvent = new MineMessageEvent();
//                    mineMessageEvent.setInform_type(mineMessageEvent.MESSAGE_INFORM);
//                    EventBus.getDefault().post(mineMessageEvent);
//                }
//                tipFirstHomeClick = false;
//                tipFirstShopClick = false;
//                tipFirstMessageClick = true;
//                tipFirstMineClick = false;

                if (btnClockList.get(2)){
                    //点击刷新消息数据
                    MineMessageEvent mineMessageEvent = new MineMessageEvent();
                    mineMessageEvent.setInform_type(mineMessageEvent.MESSAGE_INFORM);
                    EventBus.getDefault().post(mineMessageEvent);
                }
                setCurrentItem(2);


                break;
            case R.id.ll_mine:


                if (!SharedPreferencesUtil.isLogin()) {
                    startActivity(LoginPhoneActivity.getIntent(MainActivity.this, "MinePageEvent"));
                }
                btnAnimation(ll_mine);


                switchFragment(3);



//                if (tipFirstMineClick) {
//                    //点击刷新我的数据
//                    mineRefresh();
//                }
//                tipFirstHomeClick = false;
//                tipFirstShopClick = false;
//                tipFirstMessageClick = false;
//                tipFirstMineClick = true;

                if (btnClockList.get(3)){
                    //点击刷新我的数据
                    mineRefresh();
                }
                setCurrentItem(3);


                break;
            default:
                break;

        }
    }

    private void mineRefresh() {
        ++mineClick;
        if (fragmentMine != null && mineClick > 1) {
            ((FragmentMine) fragmentMine).srlMine.autoRefresh();
            ((FragmentMine) fragmentMine).nestedScrollView.smoothScrollTo(0, 0);

        }
    }

    private void mallRefresh() {
        ++mallClick;
        if (shopFragment != null && mallClick > 1) {
            ((ShopFragment) shopFragment).refreshLayout.autoRefresh();
//            ((ShopFragment) shopFragment).shopCaiLoveRv.smoothScrollToPosition(0);
            ((ShopFragment)shopFragment).nest_scrollview.smoothScrollTo(0,0);

        }
    }

    private void homeRefresh() {
        if (fragmentHome != null) {
            Fragment currentFragment = ((FragmentHome) fragmentHome).fragmentPagerAdapter.getCurrentFragment();
//            Fragment currentFragment = ((FragmentHome) home).fragmentMap.get(((FragmentHome) home).currentIndex);
            if (currentFragment instanceof FragmentRecommendLayzed) {
                ((FragmentRecommendLayzed) currentFragment).nestedScrollView.smoothScrollTo(0, 0);
                ((FragmentRecommendLayzed) currentFragment).refreshLayout.autoRefresh();
            } else if(currentFragment instanceof FragmentStandard){
                ((FragmentStandard) currentFragment).nestedScrollView.smoothScrollTo(0, 0);
                ((FragmentStandard) currentFragment).refreshLayout.autoRefresh();
            }else if (currentFragment instanceof FragmentFollow) {
                ((FragmentFollow) currentFragment).nestedScrollView.smoothScrollTo(0, 0);
                ((FragmentFollow) currentFragment).refreshLayout.autoRefresh();
            } else if (currentFragment instanceof FragmentCultivate) {
                ((FragmentCultivate) currentFragment).nestedScrollView.smoothScrollTo(0, 0);
                ((FragmentCultivate) currentFragment).courseRefresh.autoRefresh();
            } else if (currentFragment instanceof FragmentWenDa) {
                ((FragmentWenDa) currentFragment).nestedScrollView.smoothScrollTo(0, 0);
                ((FragmentWenDa) currentFragment).refreshLayout.autoRefresh();
            } else if (currentFragment instanceof FragmentAchievements) {
                ((FragmentAchievements) currentFragment).nestedScrollView.smoothScrollTo(0, 0);
                ((FragmentAchievements) currentFragment).achieveRefresh.autoRefresh();
            }

        }
    }


    /*
     * 初始化配置
     */
    private void initView() {
//        mViewPager = (ViewPager) findViewById(R.id.id_viewpage);
//        id_content = (FrameLayout) findViewById(R.id.id_content);
//        id_content.setOnClickListener(this);

        ivbtn_home = (ImageButton) findViewById(R.id.ivbtn_home);

        tv_home = (TextView) findViewById(R.id.tv_home);

        ll_home = (FrameLayout) findViewById(R.id.ll_home);
        ll_home.setOnClickListener(this);
        ivbtn_mall = (ImageView) findViewById(R.id.ivbtn_mall);

        iv_mall = (TextView) findViewById(R.id.iv_mall);

        ll_mall = (LinearLayout) findViewById(R.id.ll_mall);
        ll_mall.setOnClickListener(this);
        ivbtn_message = (ImageView) findViewById(R.id.ivbtn_message);

        tv_message = (TextView) findViewById(R.id.tv_message);

        ll_message = (LinearLayout) findViewById(R.id.ll_message);
        ll_message.setOnClickListener(this);
        ivbtn_mine = (ImageView) findViewById(R.id.ivbtn_mine);

        tv_mine = (TextView) findViewById(R.id.tv_mine);

        ll_mine = (LinearLayout) findViewById(R.id.ll_mine);
        ll_mine.setOnClickListener(this);
        tv_badge_view = (SuperTextView) findViewById(R.id.tv_badge_view);
        tv_badge_view.setOnClickListener(this);
        ll_home_normal = (LinearLayout) findViewById(R.id.ll_home_normal);

        iv_home_click = (ImageView) findViewById(R.id.iv_home_click);
        ll_home_click = (LinearLayout) findViewById(R.id.ll_home_click);


        mainViewPager = findViewById(R.id.main_viewpager);
        fragments = new ArrayList<Fragment>();
        fragmentHome = new FragmentHome();
//        fragmentHome = new FragmentHometwo();
        shopFragment = new ShopFragment();
        fragmentMyMessage = new FragmentMyMessage();
        fragmentMine = new FragmentMine();
        fragments.add(fragmentHome);
        fragments.add(shopFragment);
        fragments.add(fragmentMyMessage);
        fragments.add(fragmentMine);
        mainViewPager.setPagingEnabled(false);
        mainViewPager.setOffscreenPageLimit(5);
        mainViewPager.setAdapter(new MainPagerFragmentAdapter(getSupportFragmentManager(), fragments));
//        mainViewPager.setCurrentItem(selectPosition, false);
        switchFragment(0);

        btnClockList.add(true);
        btnClockList.add(false);
        btnClockList.add(false);
        btnClockList.add(false);
    }


    /*
     * 把所有图片变暗
     */
    private void resetImg() {

        ll_home.post(new Runnable() {
            @Override
            public void run() {
                if (isHomeBtnClick){
                    ll_home_normal.setVisibility(View.GONE);
                    ll_home_click.setVisibility(View.VISIBLE);
                }else{
                    ll_home_normal.setVisibility(View.VISIBLE);
                    ll_home_click.setVisibility(View.GONE);
                }
            }
        });


        ivbtn_mall.setImageResource(R.mipmap.activity_compare_normal);
        ivbtn_message.setImageResource(R.mipmap.activity_brand_normal);
        ivbtn_mine.setImageResource(R.mipmap.activity_my_normal);
    }

    public static Intent queryIntent(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        return intent;
    }

    public static Intent queryIntent(Context context, int fragmentIndex) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra(ARG_FRAGMENTINDEX, fragmentIndex);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        return intent;
    }

    public static Intent queryIntent(Context context, int fragmentIndex, String homeFragmentIndex) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra(ARG_FRAGMENTINDEX, fragmentIndex);
        intent.putExtra(ARG_FRAGMENTINDEX_SECOND, homeFragmentIndex);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        return intent;
    }


    public void btnAnimation(View view) {
        ObjectAnimator fangx = ObjectAnimator.ofFloat(view, "scaleX", 1f, 1.3f, 1f);
        ObjectAnimator fangy = ObjectAnimator.ofFloat(view, "scaleY", 1f, 1.3f, 1f);
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.play(fangx).with(fangy);
        animatorSet.setDuration(300);
        animatorSet.start();
    }

  /*  public void eventSwitch(int page, LinearLayout linearLayout, ImageView imageView) {
        initViewPage(page);
        mViewPager.setCurrentItem(page);
        resetImg();
//        btnAnimation(linearLayout);
        if (imageView.getId() == R.id.iv_home_click) {
           *//* if (homeIconSwitcher){
                iv_home_click.setImageResource(R.mipmap.activity_home_active_rocket);
                //使用AnimationUtils类的静态方法loadAnimation()来加载XML中的动画XML文件
                animation= AnimationUtils.loadAnimation(this, R.anim.home_translate_anim_up);
            }else {
                iv_home_click.setImageResource(R.mipmap.activity_home_active);
                //使用AnimationUtils类的静态方法loadAnimation()来加载XML中的动画XML文件
                animation= AnimationUtils.loadAnimation(this, R.anim.home_translate_anim_below);
            }
            iv_home_click.startAnimation(animation);*//*


            linearLayout.setVisibility(View.GONE);
            ll_home_click.setVisibility(View.VISIBLE);
//           imageView.setImageResource(R.mipmap.activity_home_active);
        } else if (imageView.getId() == R.id.ivbtn_mall) {
            imageView.setImageResource(R.mipmap.activity_compare_active);
        } else if (imageView.getId() == R.id.ivbtn_message) {
            imageView.setImageResource(R.mipmap.activity_brand_active);
        } else if (imageView.getId() == R.id.ivbtn_mine) {
            imageView.setImageResource(R.mipmap.activity_my_active);
        }

    }*/

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
//        super.onSaveInstanceState(outState, outPersistentState);将这一行注释掉，阻止activity保存fragment的状态,解决Fragment穿透重叠现象
    }

    //    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            // 当用户准备退出应用时，是将应用压到后台，而不是正常的关闭activity
//            moveTaskToBack(false);
//            return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }

    //火箭回调
    @Override
    public void onTop() {
        System.out.println("------------------------ontop");
        homeIconSwitcher = false;

        if (clickHomeBtnToTopFlag){//当火箭点击的时候回到顶部执行两次“融”出现的动画
            clickHomeBtnToTopFlag = false;
            return;
        }
        iv_home_click.setImageResource(R.mipmap.activity_home_active);
        //使用AnimationUtils类的静态方法loadAnimation()来加载XML中的动画XML文件
        animation = AnimationUtils.loadAnimation(this, R.anim.home_translate_anim_below);
        animation.setFillAfter(true);
        iv_home_click.startAnimation(animation);
    }

    @Override
    public void onDowning() {
        if (!homeIconSwitcher) {
            homeIconSwitcher = true;
            iv_home_click.setImageResource(R.mipmap.activity_home_active_rocket);
            //使用AnimationUtils类的静态方法loadAnimation()来加载XML中的动画XML文件
            animation = AnimationUtils.loadAnimation(this, R.anim.home_translate_anim_up);
            iv_home_click.startAnimation(animation);
        }
    }


    boolean isHomeBtnClick = false;
    private void changeBottomButton() {
        switch (selectPosition) {
            case 0:
            default:
                isHomeBtnClick = true;
                resetImg();
//                ll_home_normal.setVisibility(View.GONE);
//                ll_home_click.setVisibility(View.VISIBLE);
                break;
            case 1:
                isHomeBtnClick = false;
                resetImg();
                ivbtn_mall.setImageResource(R.mipmap.activity_compare_active);
//                ll_home_normal.setVisibility(View.VISIBLE);
//                ll_home_click.setVisibility(View.GONE);
                break;
            case 2:
                isHomeBtnClick = false;
                resetImg();
                ivbtn_message.setImageResource(R.mipmap.activity_brand_active);
//                ll_home_normal.setVisibility(View.VISIBLE);
//                ll_home_click.setVisibility(View.GONE);
                break;
            case 3:
                isHomeBtnClick = false;
                resetImg();
                ivbtn_mine.setImageResource(R.mipmap.activity_my_active);
//                ll_home_normal.setVisibility(View.VISIBLE);
//                ll_home_click.setVisibility(View.GONE);
                break;
        }
    }

    public void switchFragment(int postion) {
        this.selectPosition = postion;
        mainViewPager.setCurrentItem(selectPosition, false);
        changeBottomButton();

        //fragmentHome 切换
        if (fragmentHome != null) {
            fragmentHome.fixedLocation = currentHomeFragmentIndexStr;
        }
    }



    @Override
    public void finish() {
//        overridePendingTransition(R.anim.center_in, R.anim.center_out);
        super.finish();
    }
}
